﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DVK.SP2007.UniversalClient;
using Microsoft.SharePoint;
using DVK.SP2007.Constants;

namespace DVK.SP2007
{
    /// <summary>
    /// Mapped metadata provider that applies to in going DVK messages (documents).
    /// </summary>
    public class InMappedMetadataProvider : IMappedMetadataProvider
    {
        DvkXml _xml;
        SPFieldCollection _fields;
        /// <summary>
        /// Initializes a new instance of the <see cref="InMappedMetadataProvider"/> class.
        /// </summary>
        /// <param name="fields">The fields.</param>
        /// <param name="dvkXml">The DVK XML.</param>
        public InMappedMetadataProvider(SPFieldCollection fields, DvkXml dvkXml)
        {
            _fields = fields;
            _xml = dvkXml;
        }

        #region IMappedMetadataProvider Members

        /// <summary>
        /// Gets the mapped metada.
        /// 
        /// DvkMappingApplyingToChoices.Out is used.
        /// </summary>
        /// <param name="mappingLevel">The mapping level.</param>
        /// <param name="identifier">The identifier.</param>
        /// <returns>a list of mapped metadata.</returns>
        public List<MappedMetadata> GetMappedMetada(
                Fields.DvkMappingLevel.DvkMappingLevelChoices mappingLevel,
                string identifier)
        {
            MetadataMappingRepository metadataMappingManager =
                new MetadataMappingRepository(SPContext.Current.Web);

            //Get mapping from MetadataMapping list
            var mappings =
                metadataMappingManager.GetMapping(
                            mappingLevel,
                            identifier,
                            Fields.DvkMappingApplyingTo.DvkMappingApplyingToChoices.In
                        );

            List<MappedMetadata> mappedMetadata =
                new List<MappedMetadata>(mappings.Count);
            foreach (var item in mappings)
            {
                try
                {
                    string spFieldName = _fields.GetFieldByInternalName(item.SPFieldName).Title;
                    var fieldValue = _xml.GetElementValue(item.DvkParentElementName, item.DvkElementName);
                    mappedMetadata.Add(
                            new MappedMetadata()
                            {
                                Source = item.DvkElementName.LocalName,
                                Target = spFieldName,
                                FieldValue = (fieldValue != null ? fieldValue : string.Empty)
                            }
                        );
                }
                //Swallow exception and just continue
                catch
                {
                }
            }

            return mappedMetadata;
        }

        #endregion
    }
}
